﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace SecTool.Core.Crypto
{
    public class KeyProvider
    {
        const string Path = "PKI";

        public static RSACryptoServiceProvider GetRSA(string username)
        {
            // create instance of provider (contains generated private/public key)
            var rsaProvider = new RSACryptoServiceProvider();

            // if user already has key in pki keystore, read
            if (File.Exists(GetPathForUser(username)))
            {
                rsaProvider.FromXmlString(File.ReadAllText(GetPathForUser(username)));
            }
            // if not, save new key pair for current user
            else
            {
                Save(rsaProvider.ToXmlString(true), username);
            }

            return rsaProvider;
        }

        /// <summary>
        /// Saves key pair into "PKI" store
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="username"></param>
        private static void Save(string xml, string username)
        {
            string filepath = GetPathForUser(username);
            var file = File.CreateText(filepath);
            file.Write(xml);
            file.Close();
        }

        /// <summary>
        /// Combines path of PKI store and username
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private static string GetPathForUser(string username)
        {
            string filepath = System.IO.Path.Combine(Path, username);
            return filepath;
        }

        public static List<String> GetRecipients()
        {
            System.IO.DirectoryInfo di = new DirectoryInfo(Path);
            return di.EnumerateFiles().Select(f => f.Name).ToList();
        }
    }
}